// 管理用户数据
import { defineStore } from 'pinia'

import { loginAPI, userInfoAPI, logoutAPI, roleDetail } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由(常量路由)
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
//引入深拷贝方法
import { cloneDeep } from 'lodash-es'
import router from '@/router'
//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  console.log(asyncRoute)
  console.log(routes)
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

export const useUserStore = defineStore('userStore', {
  // 1.定义管理用户数据的state
  state: () => {
    return {
      token: GET_TOKEN(), // 用户唯一标识token
      menuRoutes: constantRoute, // 仓库存储生成菜单路由
      username: '', // 用户名
      personalInfo: {}, // 用户信息
      userRole: '', // 用户角色
      // avatar: '', //
      buttons: [], // 存储当前用户是否包含某一个按钮
    }
  },
  //异步|逻辑的地方
  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token
      SET_TOKEN(token)
    },
    // 用户登录的方法
    async userLogin(data: any) {
      const res: any = await loginAPI(data)
      console.log(res)
      if (res.code === 200) {
        // pinia仓库存储token
        this.token = res.result.token
        // 本地持久化存储token
        // localStorage.setItem('TOKEN', res.result.token)
        SET_TOKEN(res.result.token)
        // 保证当前async函数返回是一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(res.result.message))
      }
    },
    // 2.定义获取接口数据的action函数
    async userInfo() {
      const res: any = await userInfoAPI()
      console.log(res)
      //如果获取用户信息成功，存储一下用户信息
      if (res.code == 200) {
        this.username = res.result.realname
        this.personalInfo = res.result
        console.log(this.username)
        // localStorage.setItem('username', res.result.realname)
        // 获取用户角色
        const roleData: any = await roleDetail({
          roleCode: res.result.roleCode,
        })
        console.log(roleData)
        if (roleData.code === 200) {
          this.userRole = roleData.result.code
          //计算当前用户需要展示的异步路由
          const userAsyncRoute = filterAsyncRoute(
            cloneDeep(asyncRoute),
            roleData.result.powerCodes,
          )
          //菜单需要的数据整理完毕
          this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
          console.log(this.menuRoutes)
          console.log(userAsyncRoute)
          console.log(anyRoute)
          //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
          ;[...userAsyncRoute, anyRoute].forEach((route) => {
            router.addRoute(route)
          })
        }
        return 'ok'
      } else {
        // return Promise.reject(new Error(result.message))
        router.push('/login')
      }
    },
    resetInfo() {
      this.username = ''
      this.personalInfo = {}
      this.userRole = ''
      this.menuRoutes = constantRoute
    },
    //退出登录
    async userLogout() {
      //退出登录请求
      const res: any = await logoutAPI()
      console.log(res)
      if (res.code == 200) {
        this.token = ''
        this.username = ''
        REMOVE_TOKEN()
        localStorage.removeItem('username')
        return 'ok'
      } else {
        return Promise.reject(new Error(res.msg))
      }
    },
  },
})
